import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    # 1、获取cookie数据
    cart = request.COOKIES.get("cart")
    if not cart:
        return response

    # 2、对cookie值进行解码
    cookie_dict = pickle.loads(base64.b64decode(cart.encode()))

    # 3、链接数据库、将数据合并起来
    # 准备需要添加的数据
    news_carts = {}
    news_add_selected = []
    news_rem_selected = []
    for k, v in cookie_dict.items():
        news_carts[k] = v["count"]
        if v["selected"]:
            news_add_selected.append(k)
        else:
            news_rem_selected.append(k)

    # 4、链接redis数据库 将数据存储到redis里
    redis_con = get_redis_connection("shoppingcart")
    pl = redis_con.pipeline()
    pl.hmset('shopping_cart_%s' % user.id, news_carts)
    if news_add_selected:
        pl.sadd('selected_%s' % user.id, *news_add_selected)
    if news_rem_selected:
        pl.srem('selected_%s' % user.id, *news_rem_selected)
    pl.execute()

    # 5、清除cookie
    response.delete_cookie('cart')

    return response
